<?php
/**
 * @author ykm 2016/6/16
 * @describe 菜鸟快递单模板二期
 */

class logisticsmanager_ctl_admin_express_cainiao extends desktop_controller {

    public function syncTpl() {
        $logisticsType = $_GET['logisticsType'];
        try {
            $templateObj = kernel::single('logisticsmanager_waybill_' . $logisticsType);
            $templateCfg = $templateObj->template_cfg();
        } catch (Exception $e){
            die('没有该类型');
        }
        $this->pagedata['finder_id'] = $_GET['finder_id'];
        $this->pagedata['channel_type'] = $logisticsType;
        $this->pagedata['template_cfg'] = $templateCfg;
        $this->display('admin/express/sync_tpl_cainiao.html');
    }

    public function doSyncTpl() {
        $channelType = $_POST['channel_type'];
        $rs = array();
        $channel = app::get('logisticsmanager')->model('channel')->getList('channel_id,shop_id,name', array('channel_type'=>$channelType, 'status'=>'true'));
        if($channel) {
            $msg = '';
            $erpApi = kernel::single('erpapi_router_request');
            $logisticsType = kernel::single('logisticsmanager_waybill_' . $channelType);
            $templateCfg = $logisticsType->template_cfg();
            $modelTpl = app::get('logisticsmanager')->model('express_template');
            $tplIdFilter = $dealData = $allCpCode = array();
            $tplIdFilter['template_type'] = $templateCfg['template_type'];
            $rs = $erpApi->set('logistics', $channel[0]['channel_id'])->template_syncStandardTpl();


            if($rs['rsp'] == 'succ') {
                $requestResult = true;
                foreach($rs['data'] as $data) {
                    $logistics = $logisticsType->logistics($data['cp_code']);
                    if($logistics['name']) {
                        $data['source'] = $channel[0]['shop_id'];
                        $tplIdFilter['out_template_id'][] = $data['out_template_id'];
                        $allCpCode[$data['cp_code']] = $data['cp_code'];
                        $dealData[$data['tpl_index']] = $data;
                    }
                }
                $channelShop = app::get('ome')->model('shop')->getList('shop_id,node_id', array('node_type' => $templateCfg['shop_type'], 'filter_sql' => 'node_id is not null and node_id!=""'));
                $bindShop = array();
                foreach ($channelShop as $key => $value) {
                    $bindShop[] = $value['shop_id'];
                }

                $hasShopId = array();
                foreach($channel as $val) {
                    if(!$templateCfg['request_again'] && in_array($val['shop_id'], $hasShopId)) {continue;}

                    if(!in_array($val['shop_id'], $bindShop)) continue;

                    $hasShopId[] = $val['shop_id'];
                    $rs = $erpApi->set('logistics', $val['channel_id'])->template_syncUserTpl();

                    if($rs['rsp'] == 'succ') {
                        foreach($rs['data'] as $data) {
                            $data['source'] = $val['shop_id'];
                            $tplIdFilter['out_template_id'][] = $data['out_template_id'];
                            $allCpCode[$data['cp_code']] = $data['cp_code'];
                            $dealData[$data['tpl_index']] = $data;
                        }
                    } else {
                        $requestResult = false;
                        $msg .= "<br/> 电子面单来源：{$val['name']} {$templateCfg['template_name']}模板同步失败,{$rs['msg']}";
                    }
                }
                $tplData = $modelTpl->getList('template_id, out_template_id, template_type', $tplIdFilter);
                foreach($tplData as $tVal) {
                    $tplIndex = '';
                    if(strpos($tVal['template_type'] , 'standard') !== false) {
                        $tplIndex = 'standard' . '-' . $tVal['out_template_id'];
                    } elseif(strpos($tVal['template_type'] , 'user') !== false) {
                        $tplIndex = 'user' . '-' . $tVal['out_template_id'];
                    }
                    if($tplIndex && $dealData[$tplIndex]) {
                        $dealData[$tplIndex]['template_id'] = $tVal['template_id'];
                    }
                }
                $updateTplId = array();
                $printTpl = kernel::single('logisticsmanager_print_tmpl');
               
                foreach($dealData as $dVal) {
                    $dVal['control_type'] = $templateCfg['control_type'];

                    $rs = $printTpl->save($dVal);

                    if($rs['rs'] == 'succ') {
                        $updateTplId[] = $rs['data']['template_id'];
                    } else {
                        if($dVal['template_id']) {
                            $updateTplId[] = $dVal['template_id'];
                            $msg .= "<br/> template_id：{$dVal['template_id']} 更新失败,{$rs['msg']}";
                        } else {
                            $msg .= "<br/> out_template_id：{$dVal['out_template_id']} 写入失败,{$rs['msg']}";
                        }
                    }
                }

                #删除没有涉及的菜鸟模板
                if($requestResult) {
                    //$modelTpl->delete(array('template_id|notin' => $updateTplId,  'template_type'=>$templateCfg['template_type'], 'cp_code'=>$allCpCode));
                    $modelTpl->db->exec("DELETE FROM sdb_logisticsmanager_express_template WHERE template_id not in(".implode(',',$updateTplId).") AND template_type in(".implode(',',$templateCfg['template_type']).") AND cp_code in(".implode(',',$allCpCode).")");
                }
            } else {
                $shopData = app::get('ome')->model('shop')->db_dump(array('shop_id'=>$channel[0]['shop_id']), 'name');
                $msg .= "<br/> 标准{$templateCfg['template_name']}模板获取失败(店铺:{$shopData['name']}),{$rs['msg']}。";
            }
            $rs['msg'] = $msg;
        } else {
            $rs['msg'] = '电子面单来源没有'.$channelType.'类型，无需同步';
        }
        if($rs['msg']) {
            $rs['rsp'] = 'fail';
        } else {
            $rs['rsp'] = 'succ';
            if($hasShopId) {
                $shopData = app::get('ome')->model('shop')->getList('name', array('shop_id' => $hasShopId));
                $rs['msg'] = '同步店铺(';
                foreach ($shopData as $val) {
                    $rs['msg'] .= $val['name'] . ',';
                }
                $rs['msg'] = trim($rs['msg'], ',') . ')的模板完成';
            }
        }
        echo json_encode($rs);
    }
}
